package com.swak.timer;

import java.time.LocalDateTime;

import org.springframework.scheduling.support.CronExpression;

import com.swak.utils.time.DateTimes;

/**
 * 定时任务
 * 
 * @author 618lf
 */
public class Crontab {

	private final CronExpression expression;
	private volatile LocalDateTime nextDate;

	public Crontab(String expression) {
		this.expression = CronExpression.parse(expression);
		this.nextDate = this.expression.next(DateTimes.now());
	}

	public boolean canExecute() {
		return nextDate.isBefore(DateTimes.now());
	}

	public LocalDateTime nextExecuteTime() {
		this.nextDate = this.expression.next(DateTimes.now());
		return this.nextDate;
	}

	/**
	 * 如果可以执行，则执行
	 * 
	 * @param run
	 */
	public void execute(Runnable run) {
		if (this.canExecute()) {
			try {
				run.run();
			} catch (Throwable e) {
			}
			this.nextExecuteTime();
		}
	}
}
